/*
 * CS_ITEM_GACHYA.cpp
 *
 *  Created on: 2013. 11. 12.
 *      Author: mega@gamevil.com
 */

#include "../../Command.h"
#include "../../User.h"
#include "../../NUtil/Utils.h"
#include "../../NLogic/Bag.h"
#include "../../NLogic/Item.h"
#include "../../NLogic/Card.h"
#include "../../NLogic/Static.h"
#include "../../NLogic/VirtualCurrency.h"
#include "../../NResource/Static.h"

namespace ProjectZ { namespace NCommand {

void SendFailItemGachya(User * pUser, int res)
{
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(res);
	*pAck << static_cast<uint8_t>(0);
	*pAck << static_cast<uint8_t>(0);
	*pAck << static_cast<uint8_t>(0);
	pAck->MakePacket(CMD_SC_ITEM_GACHYA);
	pUser->Send(pAck);
}

void Command::CS_ITEM_GACHYA(User * pUser, ::Network::Packet * pPacket)
{
/*	CS_ITEM_GACHYA	0x2316
	{
	}

	SC_ITEM_GACHYA	0x2317
	{
		s16		ack;
		u8		u8is_event;				//할인 이벤트 여부 0: 이벤트 아님, 1: 이벤트 중
		u8		u8card_index;			// 지급되는 카드 번호 (0 ~ 2)
		u8		count		(MAX : 3)	//아이템 뽑기 일때는 (젠카드) 3장
		{
			s8		class_type;
			u8		sheet_type;
			u16		item_tid;
			u8		item_quality;
			u8		refine_step;
			u8		eff_type0;
			u8		eff_pos0;	// 기본이펙트 : 위치
			u16		eff_value0;	// 기본이펙트 : 효과치
		}
	}*/

	PREPARE_PACKET;

	int vcIndex = static_cast<int>(EM_VCINDEX_ZEN_CARD_GACHYA);

	NResource::VCResource::Flyweight * pFly = NResource::Static::InstancePtr()->GetVCRef()->GetFly(vcIndex);
	if (NULL == pFly)
	{
		DEBUGLOG("CS_ITEM_GACHYA : pFly is NULL!");
		return;
	}

	// 가격 확인
	if (static_cast<int>(pUser->GetVirtualCurrency()->GetZen()) < (pFly->_VC_PRICE * -1))
	{
		SendFailItemGachya(pUser, ACK_NOT_ENOUGH_ZEN);
		return;
	}

	NLogic::Card * pCard = pUser->GetCard();
	if (NULL == pCard)
	{
		DEBUGLOG("CS_ITEM_GACHYA : pCard is NULL!!");
		return;
	}

	int gachyaType = static_cast<int>(ItemGachyaType::EM_3_QUALITY_GACHYA);

	pCard->Clear();

	// 아이템 3종 미리 준비
	if (false == NResource::Static::InstancePtr()->GetDungeonReward()->ItemGachyaReady(pUser, gachyaType))
	{
		DEBUGLOG("CS_ITEM_GACHYA : ItemGachyaReady False");
		return;
	}

	// 지급 아이템 미리 선택
	int cardIndex = NResource::Static::InstancePtr()->GetDungeonReward()->GetItemQualityIndex(pUser, gachyaType);
	if (-1 == cardIndex)
	{
		DEBUGLOG("CS_ITEM_GACHYA : cardIndex == -1");
		return;
	}

	// 지급 아이템 포인터 가져온다.
	NLogic::Card::Data * pData = pCard->GetZenCardData(static_cast<NLogic::Card::CardItemType>(cardIndex));
	if (NULL == pData)
	{
		DEBUGLOG("CS_ITEM_GACHYA : pData is NULL!");
		return;
	}

	// 아이템 지급
	NLogic::Item::Data clsData;
	clsData.tid				= pData->tid;
	clsData.sub_type		= pData->sheetType;
	clsData.class_type		= pData->classType;
	clsData.quality			= pData->quality;
	clsData.cur_refine_step	= pData->refine;
	clsData.eff_pos[0]		= pData->effPos;
	clsData.eff_type[0]		= pData->effType;
	clsData.eff_value[0]	= pData->effValue;
	clsData.quantity		= 1;
	clsData.bag_type		= NResource::Static::InstancePtr()->GetItemResource()->GetItemBagType(clsData);

    // 아이템 뽑기는 무조건 식별아이템이 나와야 하므로,
    // 아이템의 정보를 셋팅할때 Flag값으로 사용하기 위해 일단 -99로 설정한다
    clsData.non_identity = -99;

	// 제련 단계에 따라 기본 능력치 향상
	if (0 < clsData.cur_refine_step)
	{
		NResource::BalanceData * pBalance = NResource::Static::InstancePtr()->GetBalance()->GetBalancePtr(pUser);
		if (NULL == pBalance)
		{
			DEBUGLOG("CS_ITEM_GACHYA : pBalance is NULL!");
			return;
		}

		for (int i = 0; i < clsData.cur_refine_step; i++)
		{
			int newValue = NUtil::AddPercentage(clsData.eff_value[0], pBalance->GetValue(EM_REFINE_STATS_ENHANCE_RATE));

			if (newValue == clsData.eff_value[0])
			{
				clsData.eff_value[0] += 1;
			}
			else
			{
				clsData.eff_value[0] = newValue;
			}
		}
	}

	NLogic::Bag * pBag = pUser->GetBag(static_cast<INVEN_BAG_TYPE>(clsData.bag_type));
	if (NULL == pBag)
	{
		DEBUGLOG("CS_ITEM_GACHYA : pBag is NULL! bagtype=%d", clsData.bag_type);
		return;
	}

	int ackReturn = ACK_OK;

	bool bBagFull = false;
	NLogic::Item * pItem = pBag->AddItemWithData(clsData, bBagFull);

	if (NULL == pItem)
	{
		// 인벤토리가 꽉 찬 경우 메일로 발송
		if (true == bBagFull)
		{
			ackReturn = ACK_INVEN_FULL_SEND_MAIL;

	        NLogic::MailBox::Mail::Data clsMailData;

	        clsMailData.send_user_seq       = 0;
	        clsMailData.send_user_nickname  = "GAMEVIL";
	        clsMailData.recv_user_seq       = pUser->GetUserSeq();
	        clsMailData.gift_status         = EM_GIFT_ITEM;
	        clsMailData.item                = clsData;
	        clsMailData.message             = NResource::Static::InstancePtr()->GetMailMessageResource()->GetMessageItemGachya();

			// 아이템 부가 정보 세팅
			NResource::Static::InstancePtr()->GetItemResource()->SetItemDataFromResource(pUser, clsMailData.item);

			// 아이템 뽑기는 무조건 미식별
			clsMailData.item.non_identity = 0;

	        if (false == NLogic::NFunction::SendMail(pUser, clsMailData))
	        {
	            DEBUGLOG("CS_ITEM_GACHYA : false == NLogic::NFunction::SendMail(pUser, clsMailData)");
	            return;
	        }
		}
		else
		{
            DEBUGLOG("CS_ITEM_GACHYA : NULL == pBag->AddItemWithData(clsData)");
            return;
		}
	}


	// 응답
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(ackReturn);
	*pAck << static_cast<uint8_t>(0);
	*pAck << static_cast<uint8_t>(cardIndex);
	*pAck << static_cast<uint8_t>(pCard->HasCardCount());

	for (int i = 0; i < pCard->GetMaxCount(); i++)
	{
		NLogic::Card::Data * pData = pCard->GetZenCardData(static_cast<NLogic::Card::CardItemType>(i));

		if (NULL == pData)
			continue;

		*pAck << static_cast<int8_t>(pData->classType);
		*pAck << static_cast<uint8_t>(pData->sheetType);
		*pAck << static_cast<uint16_t>(pData->tid);
		*pAck << static_cast<uint8_t>(pData->quality);
		*pAck << static_cast<uint8_t>(pData->refine);
		*pAck << static_cast<uint8_t>(pData->effType);
		*pAck << static_cast<uint8_t>(pData->effPos);
		*pAck << static_cast<uint16_t>(pData->effValue);
	}

	pAck->MakePacket(CMD_SC_ITEM_GACHYA);
	pUser->Send(pAck);

	// VC 처리
	NLogic::NFunction::VCProcess(pUser, EM_VCINDEX_ZEN_CARD_GACHYA);
}

} /*NCommand*/ } /*ProjectZ*/
